// 导入组件和工具函数
import { AppModule } from '../modules/appModule.js';
import { formatRelativeTime, truncateText } from '../modules/utils.js';
import { 
  dashboardComponent, 
  userManagementComponent, 
  postManagementComponent, 
  categoryManagementComponent, 
  postDetailComponent,
  searchComponent 
} from './components.js';

const { createApp } = Vue;

// 创建Vue应用
const app = createApp({
    components: {
        'dashboard-component': dashboardComponent,
        'user-management-component': userManagementComponent,
        'post-management-component': postManagementComponent,
        'category-management-component': categoryManagementComponent,
        'post-detail-component': postDetailComponent,
        'search-component': searchComponent
    },
    data() {
        return {
            appModule: null,
            activeTab: 'dashboard',
            loading: true,
            error: '',
            message: '',
            globalSearchTerm: '',
            searchResults: [],
            isDarkTheme: false,
            apiContent: '',
            aboutContent: ''
        };
    },
    async created() {
        // 初始化主题
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            this.isDarkTheme = true;
            document.body.classList.add('dark-theme');
        }
        
        try {
            console.log('应用初始化...');
            this.appModule = new AppModule();
            await this.appModule.init();
            console.log('应用初始化完成');
            
            // 加载API文档和关于页面内容
            await this.loadStaticContent();
        } catch (err) {
            console.error('应用初始化失败:', err);
            this.error = '应用初始化失败: ' + err.message;
        } finally {
            this.loading = false;
        }
    },
    methods: {
        async loadStaticContent() {
            try {
                // 获取API文档内容
                const apiResponse = await fetch('./partials/api-docs.html');
                this.apiContent = await apiResponse.text();
                
                // 获取关于页面内容
                const aboutResponse = await fetch('./partials/about.html');
                this.aboutContent = await aboutResponse.text();
            } catch (error) {
                console.error('加载静态内容失败:', error);
                this.apiContent = '<div class="error">加载API文档失败</div>';
                this.aboutContent = '<div class="error">加载关于页面失败</div>';
            }
        },
        switchTab(tabName) {
            this.activeTab = tabName;
            this.error = '';
            this.message = '';
            console.log('切换标签页到:', tabName);
        },
        onSearch(term) {
            // 触发搜索功能
            this.performGlobalSearch();
        },
        onSearchClear() {
            // 清除搜索
            this.clearGlobalSearch();
        },
        performGlobalSearch() {
            if (!this.globalSearchTerm.trim()) {
                this.searchResults = [];
                return;
            }

            this.searchResults = [];
            const term = this.globalSearchTerm.toLowerCase();

            // 搜索用户
            if (this.appModule && this.appModule.userModule && this.appModule.userModule.users) {
                const matchedUsers = this.appModule.userModule.users.filter(user =>
                    user.name.toLowerCase().includes(term) ||
                    user.email.toLowerCase().includes(term)
                );

                matchedUsers.forEach(user => {
                    this.searchResults.push({
                        type: 'user',
                        title: user.name,
                        subtitle: user.email,
                        id: user.id,
                        action: () => {
                            this.switchTab('users');
                            // 这里可以添加高亮特定用户的逻辑
                        }
                    });
                });
            }

            // 搜索文章
            if (this.appModule && this.appModule.postModule && this.appModule.postModule.posts) {
                const matchedPosts = this.appModule.postModule.posts.filter(post =>
                    post.title.toLowerCase().includes(term) ||
                    post.content.toLowerCase().includes(term) ||
                    post.author.toLowerCase().includes(term)
                );

                matchedPosts.forEach(post => {
                    this.searchResults.push({
                        type: 'post',
                        title: post.title,
                        subtitle: `作者: ${post.author} | ${this.formatDate(post.createdAt)}`,
                        id: post.id,
                        action: () => {
                            this.switchTab('blog');
                            // 这里可以添加高亮特定文章的逻辑
                        }
                    });
                });
            }

            // 搜索分类
            if (this.appModule && this.appModule.categoryModule && this.appModule.categoryModule.categories) {
                const matchedCategories = this.appModule.categoryModule.categories.filter(category =>
                    category.name.toLowerCase().includes(term) ||
                    category.description.toLowerCase().includes(term)
                );

                matchedCategories.forEach(category => {
                    this.searchResults.push({
                        type: 'category',
                        title: category.name,
                        subtitle: category.description,
                        id: category.id,
                        action: () => {
                            this.switchTab('categories');
                            // 这里可以添加高亮特定分类的逻辑
                        }
                    });
                });
            }

            // 搜索评论
            if (this.appModule && this.appModule.commentModule && this.appModule.commentModule.comments) {
                const matchedComments = this.appModule.commentModule.comments.filter(comment =>
                    comment.content.toLowerCase().includes(term) ||
                    comment.author.toLowerCase().includes(term)
                );

                matchedComments.forEach(comment => {
                    // 找到对应的文章
                    let postTitle = '未知文章';
                    if (this.appModule && this.appModule.postModule && this.appModule.postModule.posts) {
                        const post = this.appModule.postModule.posts.find(p => p.id === comment.postId);
                        if (post) postTitle = post.title;
                    }

                    this.searchResults.push({
                        type: 'comment',
                        title: this.truncateText(comment.content, 50),
                        subtitle: `作者: ${comment.author} | 文章: ${postTitle}`,
                        id: comment.id,
                        action: () => {
                            this.switchTab('blog');
                            // 这里可以添加高亮特定评论的逻辑
                        }
                    });
                });
            }
        },
        clearGlobalSearch() {
            this.globalSearchTerm = '';
            this.searchResults = [];
        },
        formatDate(date) {
            return date ? new Date(date).toLocaleDateString() : '';
        },
        toggleTheme() {
            this.isDarkTheme = !this.isDarkTheme;
            document.body.classList.toggle('dark-theme', this.isDarkTheme);
            localStorage.setItem('theme', this.isDarkTheme ? 'dark' : 'light');
        },
        truncateText(text, maxLength) {
            return truncateText(text, maxLength);
        },
        exportData() {
            if (!this.appModule) {
                this.error = '应用模块未初始化';
                return;
            }

            // 导出所有数据
            const exportData = {
                users: this.appModule.userModule.users,
                posts: this.appModule.postModule.posts,
                categories: this.appModule.categoryModule.categories,
                comments: this.appModule.commentModule.comments,
                exportDate: new Date().toISOString()
            };

            // 创建下载链接
            const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `blog-export-${new Date().toISOString().slice(0, 10)}.json`;
            document.body.appendChild(a);
            a.click();

            // 清理
            setTimeout(() => {
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                this.message = '数据导出成功';
            }, 100);
        }
    }
});

app.mount('#app');